package com.changgou.order.service.impl;

import com.changgou.common.pojo.Result;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.feign.SpuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.goods.pojo.Spu;
import com.changgou.order.pojo.OrderItem;
import com.changgou.order.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName: CartServiceImpl
 * @Auther: jeecg-boot
 * @Date: 2021/8/10 11:46
 * @Version 1.0
 */
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private SkuFeign skuFeign;
    @Autowired
    private SpuFeign spuFeign;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void add(Integer num, Long id, String username) {
        if(num <= 0 ){
            redisTemplate.boundHashOps("Cart_" + username).delete(id);
        }
        Result<Sku> result = skuFeign.findById(id);
        Sku sku = result.getData();
        if (sku != null) {
            OrderItem item = new OrderItem();
            Result<Spu> spuResult = spuFeign.findById(Long.valueOf(sku.getSpuId()));
            Spu spu = spuResult.getData();
            item.setSkuId(id.toString());
            item.setName(sku.getName());
            item.setNum(num);
            item.setMoney(sku.getPrice() * num);
            item.setPayMoney(sku.getPrice() * num);
            item.setImage(sku.getImage());
            item.setSpuId(sku.getSpuId());
            item.setCategoryId1(spu.getCategory1Id());
            item.setCategoryId2(spu.getCategory2Id());
            item.setCategoryId3(spu.getCategory3Id());
            //添加数据
            redisTemplate.boundHashOps("Cart_" + username).put(id,item);
        }
    }

    @Override
    public List<OrderItem> list(String username) {
        List values = redisTemplate.boundHashOps("Cart_" + username).values();
        return values;
    }
}
